#pragma once
#include <pthread.h>
#include <functional>
#include <ctime>
#include <string>

using fun = std::function<void()>;

class thread
{
private:
    static int tnum;
    static void *threadfun(void *agrv)
    {
        thread *t = (thread *)agrv;
        t->exec_cb();
        return nullptr;
    }

public:
    thread(fun _cbf)
        : tid_(0), name_(""), start_timestamp_(0), isrunning_(0), cbf_(_cbf)
    {
    }
    
    void run()
    {
        name_ = "thread" + std::to_string(tnum);
        start_timestamp_ = time(nullptr);
        isrunning_ = true;
        pthread_create(&tid_,nullptr, threadfun, (void*)this);
    }

    void join()
    {
        pthread_join(tid_,nullptr);
    }

    const std::string &name()
    {
        return name_;
    }
    uint64_t start_time()
    {
        return start_timestamp_;
    }
    bool thread_state()
    {
        return isrunning_;
    }
    void exec_cb()
    {
        cbf_();
    }
    ~thread()
    {
        join();
    }
private:
    // 线程id
    pthread_t tid_;
    // 线程名
    std::string name_;
    // 创建时间戳
    uint64_t start_timestamp_;
    // 线程状态
    bool isrunning_;
    // 回调函数
    fun cbf_;
};

int thread::tnum = 1;